<template>
  <div class="goods_wrap">
    <div class="top_box">
      <el-card class="goods_top_card">
        <el-form :inline="true" class="demo-form-inline">
          <!-- 药品 -->
          <el-form-item label="药品">
            <el-input v-model="selectGoodsParamData.name" placeholder="请输入药品名称" clearable style="width: 242px" />
          </el-form-item>

          <!-- 实验室 -->
          <el-form-item label="实验室">
            <!-- <el-input v-model="selectGoodsParamData.labAddress" placeholder="请输入实验室" style="width: 170px" clearable /> -->
            <el-select
              v-model="selectGoodsParamData.labAddress"
              filterable
              placeholder="请选择实验室"
              style="width: 200px"
              clearable
            >
              <el-option v-for="item in tabLabGoodsLabList" :key="item.id" :label="item.address" :value="item.address">
              </el-option>
            </el-select>
          </el-form-item>

          <!-- 药品柜 -->
          <el-form-item label="药品柜">
            <el-input v-model="selectGoodsParamData.code" placeholder="请输入药品柜" style="width: 200px" clearable />
          </el-form-item>

          <!-- 类别 -->
          <el-form-item label="类别">
            <el-select
              v-model="selectGoodsParamData.categoryName"
              filterable
              placeholder="请选择类别"
              style="width: 200px"
              clearable
            >
              <el-option v-for="item in categoryOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
            </el-select>
          </el-form-item>

          <!-- 科目 -->
          <el-form-item label="科目">
            <el-input v-model="selectGoodsParamData.subjectName" placeholder="请输入科目" style="width: 200px" clearable />
          </el-form-item>

          <!-- 项目 -->
          <el-form-item label="项目">
            <el-input v-model="selectGoodsParamData.projectName" placeholder="请输入项目" style="width: 200px" clearable />
          </el-form-item>

          <br />
          <el-form-item>
            <el-button type="primary" style="width: 90px" @click="querySelectClick">
              <el-icon style="margin-right: 6px"><Search /></el-icon>
              查询
            </el-button>

            <!-- 权限 -->
            <el-button v-if="userStore.userInfo.isManager == 1" type="primary" style="width: 90px" @click="addEditClick(0, null)">
              <el-icon style="margin-right: 6px"><Plus /></el-icon>
              添加
            </el-button>

            <el-button type="primary" style="width: 90px" @click="showLendGoodsDialog(1)">
              <!-- <el-icon size="18" style="margin-right: 6px"><DocumentAdd /></el-icon> -->
              <img src="./images/jiechu.svg" style="width: 18px; height: 18px; margin-right: 4px" alt="" srcset="" />
              借出
            </el-button>

            <el-button type="primary" style="width: 90px" @click="showLendGoodsDialog(2)">
              <!-- <el-icon size="18" style="margin-right: 6px"><DocumentAdd /></el-icon> -->
              <img src="./images/guihuan.svg" style="width: 18px; height: 18px; margin-right: 4px" alt="" srcset="" />
              归还
            </el-button>

            <el-button v-if="userStore.userInfo.isManager == 1" type="primary" style="width: 90px" @click="importGoodsClick">
              <el-icon size="18" style="margin-right: 6px"><DocumentAdd /></el-icon>
              导入
            </el-button>

            <el-button type="primary" style="width: 90px" @click="exportClick">
              <el-icon size="18" style="margin-right: 6px"><UploadFilled /></el-icon>
              导出
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    <div class="bottom_box">
      <el-card class="goods_bottom_card">
        <el-table
          :data="goodsTableData"
          border
          style="width: 100%"
          v-loading="isTableLoading"
          class="good_table"
          stripe
          :scrollbar-always-on="true"
          @row-dblclick="goodsTableRowDbClick"
        >
          <!-- 序号 -->
          <el-table-column prop="serialNumber" label="序号" width="70" align="center" />
          <!-- <template #default="scope, index">
              <span>{{ tabNumCompFunc(scope.row, index) }}</span>
            </template> -->
          <!-- </el-table-column> -->

          <!-- 名称 -->
          <el-table-column prop="name" label="名称" align="center" show-overflow-tooltip width="120" />

          <!-- 实验室 -->
          <el-table-column prop="labAddress" label="实验室" align="center" show-overflow-tooltip width="120" />

          <!-- 药品柜 -->
          <el-table-column prop="code" label="药品柜" align="center" show-overflow-tooltip width="100" />

          <!-- 规格 -->
          <el-table-column prop="specificDesc" label="规格" width="125" align="center" show-overflow-tooltip />

          <!-- CAS -->
          <el-table-column prop="cas" label="CAS" align="center" show-overflow-tooltip width="90" />

          <!-- 可用存量 -->
          <el-table-column prop="quantity" label="可用存量" align="center" show-overflow-tooltip width="120" />

          <!-- 借出数量 -->
          <el-table-column prop="lendQuantity" label="借出数量" align="center" show-overflow-tooltip width="120" />

          <!-- 单位 -->
          <el-table-column prop="measure" label="单位" align="center" show-overflow-tooltip width="70" />

          <!-- 类别 -->
          <el-table-column prop="categoryName" label="类别" align="center" show-overflow-tooltip width="90" />

          <!-- 制造商 -->
          <el-table-column prop="manufacturer" label="制造商" align="center" show-overflow-tooltip width="90" />

          <!-- 科目 -->
          <el-table-column prop="subjectName" label="科目" align="center" show-overflow-tooltip width="120" />

          <!-- 项目 -->
          <el-table-column prop="projectName" label="项目" align="center" show-overflow-tooltip width="120" />

          <!-- 创建时间 -->
          <!-- <el-table-column prop="gmtCreate" label="创建时间" align="center" show-overflow-tooltip /> -->

          <!-- 更新时间 -->
          <el-table-column prop="gmtModify" label="更新时间" align="center" show-overflow-tooltip width="180" />

          <!-- 操作 -->
          <el-table-column label="操作" align="center" width="120">
            <template #default="scope">
              <div class="operation_box">
                <span class="edit_text" @click="addEditClick(1, scope.row)">编辑</span>
                <!-- 删除 -->
                <el-popconfirm width="200" title="确认删除此货品吗?" @confirm="deleteGoodsFunc(scope.row)">
                  <template #reference>
                    <span class="del_text">删除</span>
                  </template>
                </el-popconfirm>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination_box">
          <el-pagination
            background
            layout="prev, pager, next"
            :total="total"
            :current-page="selectGoodsParamData.page"
            :page-size="selectGoodsParamData.size"
            @current-change="pageChange"
            @size-change="sizeChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 添加编辑表单弹窗 -->
    <el-dialog v-model="isShowAddEditFormDialog" :title="`${isFormAdd ? '添加' : '编辑'}货品`" top="6vh" width="540" draggable>
      <div class="add_edit_form_box">
        <el-form
          :model="addEditFormData"
          label-position="right"
          label-width="100px"
          ref="addEditFormRef"
          :rules="addEditFormRule"
        >
          <!-- 货品名称 -->
          <el-form-item label="货品名称" prop="name">
            <el-input placeholder="请输入货品名称" v-model="addEditFormData.name" />
          </el-form-item>

          <!-- 类别 -->
          <el-form-item label="类别" prop="categoryName">
            <el-select v-model="addEditFormData.categoryName" filterable placeholder="请选择类别" clearable>
              <el-option v-for="item in categoryOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
            </el-select>
          </el-form-item>

          <!-- 实验室地址 -->
          <el-form-item label="实验室地址" prop="labAddress">
            <!-- <el-input placeholder="请输入实验室地址" v-model="addEditFormData.labAddress" /> -->
            <el-select v-model="addEditFormData.labAddress" filterable placeholder="请选择实验室地址" clearable>
              <el-option v-for="item in laboratoryList" :key="item.label" :label="item.label" :value="item.label"> </el-option>
            </el-select>
          </el-form-item>

          <!-- 药品柜 -->
          <el-form-item label="药品柜" prop="code">
            <el-input placeholder="请输入药品柜" v-model="addEditFormData.code" />
          </el-form-item>

          <!-- 规格描述 -->
          <el-form-item label="规格描述" prop="specificDesc">
            <el-input placeholder="请输入规格描述" v-model="addEditFormData.specificDesc" />
          </el-form-item>

          <!-- 存量 -->
          <el-form-item label="存量" prop="quantity">
            <el-input placeholder="请输入存量" v-model="addEditFormData.quantity" />
          </el-form-item>

          <!-- 单位 -->
          <el-form-item label="单位" prop="measure">
            <!-- <el-input placeholder="请输入单位" v-model="addEditFormData.measure" />
              -->
            <el-select v-model="addEditFormData.measure" filterable placeholder="请选择单位" clearable>
              <el-option v-for="item in measureList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
            </el-select>
          </el-form-item>

          <!-- CAS -->
          <el-form-item label="CAS" prop="cas">
            <el-input placeholder="请输入CAS" v-model="addEditFormData.cas" />
          </el-form-item>

          <!-- 危险标识 -->
          <el-form-item label="危险标识" prop="dangerRemark">
            <el-input placeholder="请输入危险标识" v-model="addEditFormData.dangerRemark" />
          </el-form-item>

          <!-- 制造商 -->
          <el-form-item label="制造商" prop="manufacturer">
            <el-input placeholder="请输入制造商" v-model="addEditFormData.manufacturer" />
          </el-form-item>

          <!-- 价格 -->
          <el-form-item label="价格" prop="price">
            <el-input placeholder="请输入价格" v-model="addEditFormData.price" />
          </el-form-item>

          <!-- 科目 -->
          <el-form-item label="科目" prop="subjectName">
            <el-input placeholder="请输入科目" v-model="addEditFormData.subjectName" />
          </el-form-item>

          <!-- 项目 -->
          <el-form-item label="项目" prop="projectName">
            <el-input placeholder="请输入项目" v-model="addEditFormData.projectName" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addEditDialogCancelClick">取消</el-button>
          <el-button type="primary" @click="addEditDialogConfirmClick(addEditFormRef)"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 导出Excel文件条件输入弹窗 -->
    <el-dialog v-model="isShowExportDialog" title="导出表格" top="6vh" width="540" draggable>
      <div class="export_form_box">
        <el-form :model="exportExcelConditionData" label-position="right" label-width="100px">
          <!-- 实验室地址 -->
          <el-form-item label="实验室地址" prop="labAddress">
            <!-- <el-input placeholder="请输入实验室地址" v-model="exportExcelConditionData.labAddress" /> -->
            <!-- <el-select v-model="exportExcelConditionData.labAddress" filterable placeholder="请选择实验室" clearable>
              <el-option v-for="item in allLabNameList" :key="item.value" :label="item.value" :value="item.value"> </el-option>
            </el-select> -->
            <el-select v-model="exportExcelConditionData.labAddress" filterable placeholder="请选择实验室" clearable>
              <el-option v-for="item in allLabNameList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
            </el-select>
          </el-form-item>

          <!-- 药品柜 -->
          <el-form-item label="药品柜" prop="code">
            <el-input placeholder="请输入药品柜" v-model="exportExcelConditionData.code" />
          </el-form-item>

          <!-- 类别 -->
          <el-form-item label="类别" prop="categoryName">
            <el-select v-model="exportExcelConditionData.categoryName" filterable placeholder="请选择类别" clearable>
              <el-option v-for="item in categoryOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
            </el-select>
          </el-form-item>

          <!-- 科目 -->
          <el-form-item label="科目" prop="subjectName">
            <el-input placeholder="请输入科目" v-model="exportExcelConditionData.subjectName" />
          </el-form-item>

          <!-- 项目 -->
          <el-form-item label="项目" prop="projectName">
            <el-input placeholder="请输入项目" v-model="exportExcelConditionData.projectName" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="exportDialogCancelClick">取消</el-button>
          <el-button type="primary" @click="exportDialogConfirmlClick"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 导入货品弹窗 -->
    <el-dialog v-model="isShowImportGoodsDialog" title="导入货品" top="6vh" width="540" draggable>
      <div class="import_goods_box">
        <!-- 第一步 -->
        <div class="step_item_box">
          <div class="title_box">
            <el-tag type="primary" effect="dark" style="margin-right: 10px; font-weight: 600"> 1 </el-tag>
            <span class="title_text"> 下载模版文件，按照模板文件填充数据。 </span>
          </div>

          <div class="content_box">
            <div class="cb_box">
              <img class="icon_img" src="./images/excel_file_icon.svg" alt="" @click="downImportTempFunc" />
              <span class="down_text" @click="downImportTempFunc">点击下载文件</span>
            </div>
          </div>
        </div>

        <!-- 第二步 -->
        <div class="step_item_box">
          <div class="title_box">
            <el-tag type="primary" effect="dark" style="margin-right: 10px; font-weight: 600"> 2 </el-tag>
            <span class="title_text"> 上传填充好的Excel文件 </span>
          </div>
          <div class="content_box" v-loading="importFileStatus == 'loading'" element-loading-text="导入中">
            <el-upload
              class="upload-demo"
              drag
              :action="importGoodsExcelUrl"
              @error="uploadError"
              @success="uploadSuccess"
              :before-upload="importExcelBeforeUpLoad"
              :headers="{
                accessToken: userStore.$state.token
              }"
            >
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">将文件拖到这里，或者点击此处选择文件上传</div>
              <!-- <template #tip>
                <div class="el-upload__tip">jpg/png files with a size less than 500kb</div>
              </template> -->
            </el-upload>
          </div>
        </div>
        <!-- 导入提示信息模块 -->
        <div class="import_info_box" v-if="importFileStatus == 'over'">
          <div class="title">导入结果</div>
          <div class="count_box">
            <span
              >总共 <span>{{ importFileOverData.totalCount }}</span> 条</span
            >
            <span
              >成功 <span style="color: green">{{ importFileOverData.successCount }}</span> 条</span
            >
            <span
              >失败 <span style="color: red">{{ importFileOverData.errorCount }}</span> 条</span
            >
          </div>

          <!-- 导入信息列表 -->

          <!-- <div class="status_box" v-if="importFileStatus == 'loading'">
            <span v-loading="true"></span>
            <span>上传中</span>
          </div> -->
          <div style="margin-top: 12px" v-if="importFileOverData.errorRowList.length != 0">
            <span>失败行数：</span>
          </div>
          <div class="error_list_box" v-if="importFileOverData.errorRowList.length != 0">
            <span v-for="(el, indexE) in importFileOverData.errorRowList" :key="indexE"
              >第{{ el }}行<span v-if="indexE != importFileOverData.errorRowList.length - 1">、</span>
            </span>
          </div>
        </div>

        <!-- 
        <ul class="error_list_box">
          <li v-for="(el, indexE) in importFileOverData.errorRowList" :key="indexE">{{ el }}</li>
        </ul> -->
      </div>

      <!-- <template #footer>
        <div class="dialog-footer">
          <el-button @click="exportDialogCancelClick">取消</el-button>
          <el-button type="primary" @click="exportDialogConfirmlClick"> 确定 </el-button>
        </div>
      </template> -->
    </el-dialog>

    <!-- 显示货品详情信息的弹窗 -->
    <el-dialog v-model="isShowGoodDetailDialog" title="货品详情" class="good_detail_dialog" top="1vh" width="1200">
      <!-- 详情信息 -->
      <div class="good_detail_box">
        <el-descriptions class="good_descriptions_box" :column="2" size="large" border>
          <!-- 货品名称 -->
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                <i class="iconfont icon-huopin"></i>
                货品名称
              </div>
            </template>
            {{ currentGoodDetailInfo.name }}
          </el-descriptions-item>
          <!-- 实验室 -->
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                <i class="iconfont icon-shiyanshi"></i>
                实验室
              </div>
            </template>
            {{ currentGoodDetailInfo.labAddress }}
          </el-descriptions-item>
          <!-- 药品柜 -->
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                <i class="iconfont icon-guizi_o"></i>
                药品柜
              </div>
            </template>
            {{ currentGoodDetailInfo.code }}-
          </el-descriptions-item>
          <!-- 规格 -->
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                <i class="iconfont icon--shangpinguige-gai-"></i>
                规格
              </div>
            </template>
            {{ currentGoodDetailInfo.specificDesc }}
          </el-descriptions-item>
          <!-- 可用存量 -->
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                <i class="iconfont icon-kucunliang-copy"></i>
                可用存量
              </div>
            </template>
            {{ currentGoodDetailInfo.quantity }}
          </el-descriptions-item>
          <!-- 借出数量 -->
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                <i class="iconfont icon-kucunliang-copy"></i>
                借出数量
              </div>
            </template>
            {{ currentGoodDetailInfo.lendQuantity }}
          </el-descriptions-item>
          <!-- 危险标识 -->
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                <i class="iconfont icon-duliang"></i>
                危险标识
              </div>
            </template>
            {{ currentGoodDetailInfo.dangerRemark }}
          </el-descriptions-item>
          <!-- 单位 -->
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                <i class="iconfont icon-duliang"></i>
                单位
              </div>
            </template>
            {{ currentGoodDetailInfo.measure }}
          </el-descriptions-item>
          <!-- CAS -->
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                <i class="iconfont icon-CAS"></i>
                CAS
              </div>
            </template>
            {{ currentGoodDetailInfo.cas }}
          </el-descriptions-item>
          <!-- 价格 -->
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                <i class="iconfont icon-jiage"></i>
                价格
              </div>
            </template>
            {{ currentGoodDetailInfo.price }}
          </el-descriptions-item>

          <!-- 类别 -->
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                <i class="iconfont icon-icon_leibie"></i>
                类别
              </div>
            </template>
            {{ currentGoodDetailInfo.categoryName }}
          </el-descriptions-item>
          <!-- 制造商 -->
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                <i class="iconfont icon-zhizaoshangbujian"></i>
                制造商
              </div>
            </template>
            {{ currentGoodDetailInfo.manufacturer }}
          </el-descriptions-item>
          <!-- 科目 -->
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                <i class="iconfont icon-kemuguanli-"></i>
                科目
              </div>
            </template>
            {{ currentGoodDetailInfo.subjectName }}
          </el-descriptions-item>
          <!-- 项目 -->
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                <i class="iconfont icon-xiangmu"></i>
                项目
              </div>
            </template>
            {{ currentGoodDetailInfo.projectName }}
          </el-descriptions-item>
          <!-- 创建时间 -->
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                <i class="iconfont icon-chuangjianshijian"></i>
                创建时间
              </div>
            </template>
            {{ currentGoodDetailInfo.gmtCreate }}
          </el-descriptions-item>
          <!-- 更新时间 -->
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                <i class="iconfont icon-gengxinshijian"></i>
                更新时间
              </div>
            </template>
            {{ currentGoodDetailInfo.gmtModify }}
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 货品借出记录 -->
      <div class="goods_lend_log_box">
        <div class="title_box">
          <img class="log_icon_img" src="./images/log.png" alt="" />
          <span class="label">借出记录</span>
        </div>
        <div class="table_box">
          <el-table
            class="good_lend_log_table"
            v-loading="isLendReturnLogTableLoading"
            :data="goodsLendLogData"
            border
            size="mini"
            :scrollbar-always-on="true"
          >
            <!-- 货品名称 -->
            <el-table-column prop="tbGoodsName" label="货品名称" align="center" show-overflow-tooltip />

            <!-- 操作类型 -->
            <el-table-column prop="makeName" label="操作类型" align="center" show-overflow-tooltip>
              <template #default="scope">
                <el-tag effect="dark" type="danger" v-if="scope.row.makeName == '借出'"> {{ scope.row.makeName }}</el-tag>
                <el-tag effect="dark" type="success" v-if="scope.row.makeName == '归还'"> {{ scope.row.makeName }}</el-tag>
              </template>
            </el-table-column>

            <!-- 借出/归还数量 -->
            <el-table-column prop="makeQuantity" label="借出/归还数量" width="120" align="center" show-overflow-tooltip>
              <template #default="scope">
                <span :class="`lend_return_num_span ${scope.row.makeName == '借出' ? 'red' : 'green'}`">{{
                  scope.row.makeQuantity
                }}</span>
              </template>
            </el-table-column>

            <!-- 剩余可用存量 -->
            <el-table-column prop="quantity" label="剩余可用存量" width="120" align="center" show-overflow-tooltip>
            </el-table-column>

            <!-- 操作人 -->
            <el-table-column prop="userName" label="操作人" align="center" show-overflow-tooltip />

            <!-- 操作时间 -->
            <el-table-column prop="createTime" label="操作时间" align="center" show-overflow-tooltip> </el-table-column>

            <!-- 备注 -->
            <el-table-column prop="lendDesc" label="备注" align="center" show-overflow-tooltip> </el-table-column>
          </el-table>
          <div class="good_lend_log_table_pagination_box">
            <el-pagination
              layout="prev, pager, next"
              :total="lendReturnLogTableTotal"
              @change="lendReturnLogTabPaginationChange"
            />
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 借出货品弹窗 -->
    <el-dialog
      class="lend_goods_dialog"
      :title="`${isLendOrReturn == 1 ? '借出' : '归还'}货品`"
      v-model="isShowLendGoodsDialog"
      top="5vh"
      width="1140"
      @close="lendGoodsCancelClick"
    >
      <div class="lend_goods_dialog_wrap">
        <div class="lend_goods_box">
          <el-card class="lend_goods_item_box" v-for="(lgsl, indexG) in lendGoodsSubList" :key="indexG">
            <!-- 头部 -->
            <div class="item_header">
              <i data-v-329ecf1a="" class="iconfont icon-goods" style="font-size: 16px; font-weight: bold"></i>
              <span class="title" style="position: relative; left: -4px; top: -1px">
                {{ `货品${indexG + 1}` }}
              </span>
              <!-- <el-icon class="del_icon" color="red" size="20"><DeleteFilled /></el-icon> -->
              <img class="del_img" src="./images/close.svg" alt="" @click="delLendGoodsItemClick(lgsl)" />
            </div>

            <!-- 主体 -->
            <div class="goods_name_box">
              <span class="label">货品名称</span>
              <el-select
                v-model="lgsl.id"
                filterable
                clearable
                remote
                reserve-keyword
                placeholder="请输入货品名称进行搜索"
                :remote-method="remoteMethod"
                :loading="isLendGoodsLoading"
                style="width: 220px"
                @change="
                  e => {
                    lendGoodsSelectChange(e, lgsl.uid);
                  }
                "
                @clear="lendGoodsSelectClear"
              >
                <el-option v-for="(lagl, indexL) in lendAllGoodsList" :key="indexL" :label="lagl.name" :value="lagl.id" />
              </el-select>
            </div>
            <div class="goods_num_box">
              <span class="label">{{ isLendOrReturn == 1 ? "借出" : "归还" }}数量</span>
              <el-input-number
                v-if="isLendOrReturn == 1"
                v-model="lgsl.lendQuantity"
                :min="0"
                :max="lendReturnMaxNumF(lgsl.quantity)"
              />
              <el-input-number v-if="isLendOrReturn == 2" v-model="lgsl.lendQuantity" :min="0" :max="lgsl.yLendQuantity" />
              <span :class="qSC(lgsl.quantity)" v-if="isShowQNF(lgsl.quantity, lgsl.id) && isLendOrReturn == 1"
                >可借数量：{{ lgsl.quantity }}</span
              >
              <span :class="qSC(lgsl.yLendQuantity)" v-if="isShowQNF(lgsl.yLendQuantity, lgsl.id) && isLendOrReturn == 2"
                >已借数量：{{ lgsl.yLendQuantity }}</span
              >
            </div>
            <div class="goods_desc_box">
              <span class="label">备注</span>
              <el-input
                v-model="lgsl.lendReturnDesc"
                style="width: 220px; margin-left: 66px; height: 40px"
                type="textarea"
                placeholder="请输入备注"
              />
            </div>
          </el-card>
          <div class="add_lend_goods_item" @click="addLendGoodsItemClick">
            <el-icon class="plus_icon" size="30"><Plus /></el-icon>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="lendGoodsCancelClick">取消</el-button>
          <el-button :loading="isShowLendDialogConfirmLoading" type="primary" @click="lendGoodsConfirmClick"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, ref } from "vue";
import "./index.scss";
export default defineComponent({
  name: "Goods"
});
</script>
<script lang="ts" setup>
import {
  selectTbGoodsByPageApi,
  selectCategoryListApi,
  selectLaboratoryListApi,
  addTbGoodsApi,
  editTbGoodsApi,
  deleteGoodsApi,
  exportExcelApi,
  selectAllLabApi,
  tbLabSelectByGoodsApi,
  lendTbGoodsApi,
  returnTbGoodsApi,
  lendGoodsSubListApi
} from "@/api/modules/goods/index";
import {
  GoodsListType,
  GoodsType,
  GoodsSelectParamType,
  AddEditFormDataType,
  ExportExcelConditionDataType,
  selectGoodsLabListType
} from "@/api/modules/goods/type";
import { ElMessage } from "element-plus";
// import { MeasureListType } from "@/api/modules/measure/type";
import { selectMeasureListApi } from "@/api/modules/measure/index";
import FileSaver from "file-saver";
import { importGoodsExcelUrl } from "@/libs/import";
import { downImportTempUrl } from "@/libs/down";
import { useUserStore } from "@/stores/modules/user";
import dayjs from "dayjs";
import { v4 as uuidv4 } from "uuid";

// 是否是管理员
// const isManage = ref(false);

const userStore = useUserStore();

// 弹窗是借出还是归还的标识
const isLendOrReturn = ref("");

// 是否显示借出货品弹窗的标识
const isShowLendGoodsDialog = ref(false);

// 借出货品列表加载标识
const isLendGoodsLoading = ref(false);

// 借出/归还数量最大数函数
const lendReturnMaxNumF = q => {
  let num = 0;
  if (isLendOrReturn.value == 1) {
    if (q != 0 && q != null && q != undefined) {
      num = q;
    } else {
      num = 0;
    }
  } else if (isLendOrReturn.value == 2) {
    num = 9999999;
  }

  return num;
  // lgsl.quantity != 0 && lgsl.quantity != null && lgsl.quantity != undefined && isLendOrReturn == 1
  //                   ? lgsl.quantity
  //                   : 0
};

// 添加借出货品项点击事件
const addLendGoodsItemClick = () => {
  // 判断是否存在一个
  if (lendGoodsSubList.value.length <= 0) {
    lendGoodsSubList.value.push({
      uid: uuidv4(),
      id: null,
      lendQuantity: 0,
      lendReturnDesc: "",
      quantity: 0,
      yLendQuantity: 0
    });
  } else {
    // 先判断上一个是否填写完整
    let lastItem = lendGoodsSubList.value[lendGoodsSubList.value.length - 1];
    console.log("lastItem", lastItem);
    if (lastItem.id == null) {
      ElMessage.warning("请将上一个货品信息填写完整");
    } else {
      lendGoodsSubList.value.push({
        uid: uuidv4(),
        id: null,
        lendQuantity: 0,
        lendReturnDesc: "",
        quantity: 0,
        yLendQuantity: 0
      });
    }
    let oldIDs = [];
    // lendGoodsSubList.value.forEach(item => {
    //   oldIDs.push(item.id);
    // });

    // lendAllGoodsList.value.forEach(item => {
    //   if (oldIDs.indexOf(item.id) != -1) {
    //     item.isDisabled = true;
    //   }
    // });
  }
};

// 删除借出货品项点击事件
const delLendGoodsItemClick = item => {
  console.log("删除", item);
  lendGoodsSubList.value = lendGoodsSubList.value.filter(lg => {
    return lg.uid != item.uid;
  });
  // let oldIDs = [];
  // lendGoodsSubList.value.forEach(items => {
  //   oldIDs.push(items.id);
  // });

  // lendAllGoodsList.value.forEach(items => {
  //   if (oldIDs.indexOf(items.id) != -1) {
  //     item.isDisabled = true;
  //   }
  // });
};

// 借出货品select组件remoteMethod
const remoteMethod = query => {
  if (query) {
    queryAllLendGoodsParams.value.name = query;
    selectAllLendTbGoods();
  }
};

// 借出货品列表
const lendGoodsSubList = ref([
  {
    uid: uuidv4(),
    id: null,
    lendQuantity: 0,
    quantity: 0,
    lendReturnDesc: "",
    yLendQuantity: 0
  }
]);

// 显示借出货品弹窗方法
const showLendGoodsDialog = type => {
  isLendOrReturn.value = type;
  isShowLendGoodsDialog.value = true;
  // setTimeout(() => {
  //   selectAllLendTbGoods();
  // }, 200);
};

// 借出货品名称change事件
const lendGoodsSelectChange = (e, uid) => {
  console.log(e);
  console.log(uid);

  if (e) {
    // 判断该货品是否已经添加
    let hArr = [];
    lendGoodsSubList.value.forEach(item => {
      if (item.id == e) {
        hArr.push(item.uid);
      }
    });
    if (hArr.length > 1) {
      ElMessage.warning("已添加此货品，请勿重复添加");
      console.log(hArr);
      lendGoodsSubList.value.forEach(item => {
        if (item.uid == hArr[hArr.length - 1]) {
          console.log("要重置项 ");
          item.id = null;
        }
      });
      return;
    }

    let tItem = lendAllGoodsList.value.filter(item => item.id == e)[0];

    console.log("tItem", tItem);

    lendGoodsSubList.value.forEach(item => {
      if (item.id == e) {
        item.lendQuantity = 0;
        item.quantity = tItem.quantity;
        item.yLendQuantity = tItem.yLendQuantity;
      }
    });
  } else {
    lendGoodsSubList.value.forEach(item => {
      if (item.uid == uid) {
        item.lendQuantity = 0;
        item.quantity = undefined;
        item.yLendQuantity = 0;
      }
    });
  }

  // lendAllGoodsList.value = lendAllGoodsListY.value;
};

// 借出货品名称claer事件
const lendGoodsSelectClear = e => {
  console.log("清空了", e);
};

// 借出/归还 货品弹窗取消点击事件
const lendGoodsCancelClick = () => {
  isShowLendGoodsDialog.value = false;
  lendGoodsSubList.value = [
    {
      uid: uuidv4(),
      id: null,
      lendQuantity: 0,
      quantity: 0,
      lendReturnDesc: "",
      yLendQuantity: 0
    }
  ];
};

// 借出/归还 货品弹窗确定按钮加载标识
const isShowLendDialogConfirmLoading = ref(false);

// 借出/归还 货品弹窗确定点击事件
const lendGoodsConfirmClick = () => {
  // 判断是借出还是归还
  if (isLendOrReturn.value == 1) {
    lendTbGoodsFunc();
  } else if (isLendOrReturn.value == 2) {
    returnTbGoodsFunc();
  }
};

// 借出请求函数
const lendTbGoodsFunc = async () => {
  isShowLendDialogConfirmLoading.value = true;

  // 判断有没有可用存量为0的货品或者没选择货品名称的
  let isSelectGood = false;
  let qWS = false;
  lendGoodsSubList.value.forEach(item => {
    console.log(item);
    if (item.lendQuantity == 0) {
      qWS = true;
    }
    if (!item.id) {
      isSelectGood = true;
    }
  });
  if (isSelectGood) {
    ElMessage.warning("请选择货品");
    isShowLendDialogConfirmLoading.value = false;
    return;
  }
  if (qWS) {
    ElMessage.warning("借出数量不能为 0");
    isShowLendDialogConfirmLoading.value = false;
    return;
  }

  // 提交数据
  let sData = lendGoodsSubList.value.map(item => {
    return {
      id: item.id,
      makeQuantity: item.lendQuantity,
      lendReturnDesc: item.lendReturnDesc
    };
  });

  await lendTbGoodsApi(sData)
    .then(res => {
      console.log("借出成功");
      ElMessage.success("借出成功");
      isShowLendGoodsDialog.value = false;
    })
    .catch(() => {
      console.log("借出失败");
      ElMessage.error("借出失败");
    })
    .finally(() => {
      isShowLendDialogConfirmLoading.value = false;
      lendGoodsSubList.value = [
        {
          uid: uuidv4(),
          id: null,
          lendQuantity: 0,
          quantity: 0,
          lendReturnDesc: ""
        }
      ];
      selectTbGoodsByPageFunc();
      selectCategoryListFunc();
      selectMeasureListFunc();
      selectLaboratoryListFunc();
      selectAllLabFunc();
      tbLabSelectByGoodsFunc();
      selectTbGoodsByPageFunc();
      selectAllLendTbGoods(true);
    });

  console.log(lendTbGoodsApi);
};

const returnTbGoodsFunc = async () => {
  console.log("归还函数");
  isShowLendDialogConfirmLoading.value = true;

  // 判断是否是空数据
  if (lendGoodsSubList.value.length == 0) {
    ElMessage.error("请添加货品");
    return;
  }

  // 判断有没有可用存量为0的货品或者没选择货品名称的
  let isSelectGood = false;
  let qWS = false;
  lendGoodsSubList.value.forEach(item => {
    console.log(item);
    if (item.lendQuantity == 0) {
      qWS = true;
    }
    if (!item.id) {
      isSelectGood = true;
    }
  });
  if (isSelectGood) {
    ElMessage.warning("请选择货品");
    isShowLendDialogConfirmLoading.value = false;
    return;
  }
  if (qWS) {
    ElMessage.warning("归还数量不能为 0");
    isShowLendDialogConfirmLoading.value = false;
    return;
  }

  // 提交数据
  let sData = lendGoodsSubList.value.map(item => {
    return {
      id: item.id,
      makeQuantity: item.lendQuantity,
      lendReturnDesc: item.lendReturnDesc
    };
  });

  await returnTbGoodsApi(sData)
    .then(res => {
      console.log("归还成功");
      ElMessage.success("归还成功");
      isShowLendGoodsDialog.value = false;
    })
    .catch(() => {
      console.log("归还失败");
      ElMessage.error("归还失败");
    })
    .finally(() => {
      isShowLendDialogConfirmLoading.value = false;
      lendGoodsSubList.value = [
        {
          uid: uuidv4(),
          id: null,
          lendQuantity: 0,
          quantity: 0,
          lendReturnDesc: ""
        }
      ];
      selectTbGoodsByPageFunc();
      selectCategoryListFunc();
      selectMeasureListFunc();
      selectLaboratoryListFunc();
      selectAllLabFunc();
      tbLabSelectByGoodsFunc();
      selectTbGoodsByPageFunc();
      selectAllLendTbGoods(true);
    });

  console.log(lendTbGoodsApi);
};

// 隐藏借出货品弹窗方法
// const hideLendGoodsDialog = () => {
//   isShowLendGoodsDialog.value = false;
// };

// 判断存量是否为0，返回不同的class
const qSC = q => {
  return q == 0 ? "quantity red" : "quantity";
};

// 判断是否显示存量的函数
const isShowQNF = (q, id) => {
  let flag;
  if (q != undefined && q != null && id) {
    flag = true;
  } else {
    flag = false;
  }
  return flag;
};

// 将空值转换为横杠的函数
// const disposeNullValueFunc = value => {
//   console.log("--value", value);
//   let rValue;
//   if (value == null || value == undefined || value == "") {
//     rValue = "--";
//   } else {
//     rValue = value;
//   }
//   return rValue;
// };

// 货品表格行双击事件
const goodsTableRowDbClick = e => {
  console.log("行双击", e);
  currentGoodDetailInfo.value = JSON.parse(JSON.stringify(e));
  // for (let eKey in e) {
  //   e[eKey] = disposeNullValueFunc(JSON.parse(JSON.stringify(e[eKey])));
  // }
  selectGoodsLendRetParams.value.tbGoodsId = e.id;
  selectGoodsLendRetParams.value.page = 1;
  selectGoodsLendLogDataFunc();
  isShowGoodDetailDialog.value = true;
};

// 显示货品详情的弹窗标识
const isShowGoodDetailDialog = ref(false);

// 当前双击的货品详情信息
const currentGoodDetailInfo = ref<GoodsType>({});

// 显示导入货品弹窗的标识
const isShowImportGoodsDialog = ref(false);

// 导入货品点击事件
const importGoodsClick = () => {
  isShowImportGoodsDialog.value = true;
  importFileStatus.value = "not";
  importFileOverData.value = {
    // 所有条数
    totalCount: 0,
    // 成功条数
    successCount: 0,
    // 失败条数
    errorCount: 0,
    // 失败行数信息
    errorRowList: []
  };
  // downImportTempFunc();
};

const importExcelBeforeUpLoad = e => {
  console.log("开始导入");
  importFileStatus.value = "loading";
  let flag;
  if (e.name.indexOf(".xls") != -1 || e.name.indexOf(".xlsx") != -1) {
    flag = true;
  } else {
    flag = false;
    ElMessage.error("只支持Excel导入!");
  }
  return flag;
};

// 导入文件状态
/*
   无操作     not
   加载中     loading
   导入完成   over
*/
const importFileStatus = ref("not");

// 导入文件结果数据
const importFileOverData = ref({
  // 所有条数
  totalCount: 0,
  // 成功条数
  successCount: 0,
  // 失败条数
  errorCount: 0,
  // 失败行数信息
  errorRowList: []
});

const uploadError = e => {
  console.log("上传失败", e);
  importFileStatus.value = "error";
  ElMessage.error("导入失败!");
};

const uploadSuccess = e => {
  console.log("上传请求成功", e); // 更新状态
  importFileStatus.value = "over";
  // if (e.result == "success") {

  //   ElMessage.success(e.data);
  // } else if (e.result == "error") {
  //   // 更新状态
  //   importFileStatus.value = "error";
  // }

  // 处理导入结果数据
  console.log("导入结果数据", e.data);
  let overData = e.data;
  let nImportFileOverData = importFileOverData.value;

  // 处理总条数
  let totalCount = Number(overData.split("共")[1].split("条记录")[0]);
  nImportFileOverData.totalCount = totalCount;
  console.log("总条数：", totalCount);

  // 处理成功条数
  let successCount = Number(overData.split("成功：")[1].split(",")[0]);
  console.log("成功条数：", successCount);
  nImportFileOverData.successCount = successCount;

  // 处理失败条数
  let errorCount = Number(overData.split("失败：")[1].split("\n")[0]);
  console.log("失败条数：", errorCount);
  nImportFileOverData.errorCount = errorCount;

  // 处理失败行数信息
  let nErrorRowList = [];
  let errorRow = overData.split("失败：")[1].split("\n");
  errorRow.shift();
  errorRow.forEach(item => {
    let rowNumber = Number(item.replace(/\D/g, ""));
    nErrorRowList.push(rowNumber);
  });
  console.log("失败行数信息：", nErrorRowList);
  nImportFileOverData.errorRowList = nErrorRowList;

  selectGoodsParamData.value.page = 1;

  importFileOverData.value = nImportFileOverData;
  console.log("导入结果", importFileOverData.value);
  selectTbGoodsByPageFunc();
};

// const uploadChange = e => {
//   console.log(e);
//   if (e.status == "ready") {
//     console.log("开始");
//   } else if (e.status == "fail") {
//     console.log("失败");
//   }
// };

// 显示导出弹窗的标识
const isShowExportDialog = ref(false);

// 导出Excel表格条件数据
const exportExcelConditionData = ref<ExportExcelConditionDataType>({
  labAddress: "",
  code: "",
  categoryName: "",
  subjectName: "",
  projectName: ""
});

// 下载导入模版请求函数
const downImportTempFunc = async () => {
  // await downImportTempApi()
  //   .then(res => {
  //     console.log(res);
  //     FileSaver.saveAs(res, "tbGoodsTemp");
  //     // ElMessage.success("下载模版成功")
  //   })
  //   .catch(() => {
  //     ElMessage.error("导出失败");
  //   })
  //   .finally(() => {
  //     // isShowImportGoodsDialog.value =
  //   });
  window.open(downImportTempUrl);
};

// 导出点击事件
const exportClick = () => {
  isShowExportDialog.value = true;
};

// 清空Excel表格条件数据
const clearExportExcelConditionData = () => {
  exportExcelConditionData.value = {
    labAddress: "",
    code: "",
    categoryName: "",
    subjectName: "",
    projectName: ""
  };
};

// 导出表格弹窗的取消点击事件
const exportDialogCancelClick = () => {
  isShowExportDialog.value = false;
  clearExportExcelConditionData();
};

// 导出表格弹窗的确定点击事件
const exportDialogConfirmlClick = () => {
  exportExcelFunc();
};

// 匹配导出实验室地址函数
const matLabAddress = id => {
  return allLabNameList.value.filter(item => {
    return item.value == id;
  })[0].label;
};

// 下载Excel表格的事件
const exportExcelFunc = async () => {
  let data = exportExcelConditionData.value;
  data.labAddress = matLabAddress(data.labAddress);
  console.log("导出提交数据", data);

  await exportExcelApi(data)
    .then(res => {
      console.log(res);
      FileSaver.saveAs(res, "货品导出数据");
      ElMessage.success("导出成功,等待下载!");
    })
    .catch(err => {
      ElMessage.error("导出失败!");
    })
    .finally(() => {
      isShowExportDialog.value = false;
      clearExportExcelConditionData();
    });
};

// 实验室列表
const laboratoryList = ref<{ label: string; value: number }[]>([]);

// 查询实验室列表的函数
const selectLaboratoryListFunc = async () => {
  await selectLaboratoryListApi().then(res => {
    laboratoryList.value = res.data.map(item => {
      return {
        label: item.address,
        value: item.id
      };
    });
  });
};

// 度量列表数据
const measureList = ref<{ label: string; value: string }[]>([]);

// 查询度量列表的函数
const selectMeasureListFunc = async () => {
  await selectMeasureListApi().then(res => {
    measureList.value = res.data.map(item => {
      return {
        label: item.name,
        value: item.name
      };
    });
  });
};

// 添加/编辑表单Ref
const addEditFormRef = ref<any>(null);

// 添加/编辑表单数据
const addEditFormData = ref<AddEditFormDataType>({
  id: null,
  fileId: null,
  labId: null,
  labAddress: "", //
  code: "", //
  name: "", //
  specificDesc: "", //
  cas: "",
  dangerRemark: "",
  manufacturer: "",
  measure: "",
  categoryId: null,
  categoryName: "",
  quantity: "", //
  threshold: "",
  price: "",
  subjectName: "",
  projectName: ""
});

// 添加/编辑表单校验规则
const addEditFormRule = ref({
  name: [{ required: true, message: "请输入药品名称", trigger: "blur" }],
  code: [{ required: true, message: "请输入药品柜", trigger: "blur" }],
  labAddress: [{ required: true, message: "请输入实验室地址", trigger: "blur" }],
  quantity: [{ required: true, message: "请输入实验室地址", trigger: "blur" }],
  categoryName: [{ required: true, message: "请输入实验室地址", trigger: "blur" }]
});

// 表单是添加还是编辑的标识
const isFormAdd = ref(false);

// 显示添加/编辑表单弹窗的标识
const isShowAddEditFormDialog = ref(false);

// 表单查询-类别Options
const categoryOptions = ref<{ label: string; value: string }[]>([]);

// 添加/编辑弹窗取消点击事件
const addEditDialogCancelClick = () => {
  isShowAddEditFormDialog.value = false;
  clearAddEditFormDataFunc();
  addEditFormRef.value.resetFields();
};

// 添加/编辑表单内容清空函数
const clearAddEditFormDataFunc = () => {
  addEditFormData.value = {
    id: null,
    fileId: null,
    labId: null,
    labAddress: "", //
    code: "", //
    name: "", //
    specificDesc: "", //
    cas: "",
    dangerRemark: "",
    manufacturer: "",
    measure: "",
    categoryId: null,
    categoryName: "",
    quantity: "", //
    threshold: "",
    price: "",
    subjectName: "",
    projectName: ""
  };
};

// 根据实验室地址匹配实验室id的函数
const selectLabIdByLabName = labName => {
  return laboratoryList.value.filter(item => {
    return item.label == labName;
  })[0].value;
};

// 添加/编辑弹窗确定点击事件
const addEditDialogConfirmClick = async formRef => {
  console.log(1);

  if (!formRef) return;
  await formRef.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      console.log("表单数据", addEditFormData.value);

      // 判断是添加还是修改，走不同的请求路线
      if (isFormAdd.value) {
        addTbGoodsFunc({
          fileId: addEditFormData.value.fileId,
          // labId: addEditFormData.value.labId,
          labId: selectLabIdByLabName(addEditFormData.value.labAddress),
          labAddress: addEditFormData.value.labAddress,
          code: addEditFormData.value.code,
          name: addEditFormData.value.name,
          specificDesc: addEditFormData.value.specificDesc,
          cas: addEditFormData.value.cas,
          dangerRemark: addEditFormData.value.dangerRemark,
          manufacturer: addEditFormData.value.manufacturer,
          measure: addEditFormData.value.measure,
          categoryId: addEditFormData.value.categoryId,
          categoryName: addEditFormData.value.categoryName,
          quantity: addEditFormData.value.quantity,
          threshold: addEditFormData.value.threshold,
          price: addEditFormData.value.price,
          subjectName: addEditFormData.value.subjectName,
          projectName: addEditFormData.value.projectName
        });
      } else {
        editTbGoodsFunc({
          id: addEditFormData.value.id,
          fileId: addEditFormData.value.fileId,
          labId: selectLabIdByLabName(addEditFormData.value.labAddress),
          labAddress: addEditFormData.value.labAddress,
          code: addEditFormData.value.code,
          name: addEditFormData.value.name,
          specificDesc: addEditFormData.value.specificDesc,
          cas: addEditFormData.value.cas,
          dangerRemark: addEditFormData.value.dangerRemark,
          manufacturer: addEditFormData.value.manufacturer,
          measure: addEditFormData.value.measure,
          categoryId: addEditFormData.value.categoryId,
          categoryName: addEditFormData.value.categoryName,
          quantity: addEditFormData.value.quantity,
          threshold: addEditFormData.value.threshold,
          price: addEditFormData.value.price,
          subjectName: addEditFormData.value.subjectName,
          projectName: addEditFormData.value.projectName
        });
      }
      isShowAddEditFormDialog.value = false;
      formRef.resetFields();
    } else {
      console.log("error submit!", fields);
    }
  });
};

// 货品删除点击事件
const deleteGoodsFunc = async row => {
  await deleteGoodsApi(row.id)
    .then(res => {
      ElMessage.success("删除成功");
    })
    .catch(err => {
      ElMessage.error("删除失败");
    })
    .finally(() => {
      selectTbGoodsByPageFunc();
    });
};

// 添加货品请求函数
const addTbGoodsFunc = async data => {
  console.log("表单数据", addEditFormData.value);

  await addTbGoodsApi(data)
    .then(res => {
      ElMessage.success("添加成功");
      isShowAddEditFormDialog.value = false;
    })
    .catch(err => {
      ElMessage.error("添加失败");
    })
    .finally(() => {
      selectTbGoodsByPageFunc();
      clearAddEditFormDataFunc();
    });
};

// 编辑货品请求函数
const editTbGoodsFunc = async data => {
  console.log("表单数据", addEditFormData.value);
  await editTbGoodsApi(data)
    .then(res => {
      ElMessage.success("修改成功");
      isShowAddEditFormDialog.value = false;
    })
    .catch(err => {
      ElMessage.error("修改失败");
    })
    .finally(() => {
      selectTbGoodsByPageFunc();
      clearAddEditFormDataFunc();
    });
};

// 编辑请求函数

// 添加/编辑点击事件
const addEditClick = (type, row: GoodsType | null) => {
  console.log(row);
  console.log(type);
  isShowAddEditFormDialog.value = true;
  type == 1 ? (isFormAdd.value = false) : (isFormAdd.value = true);

  // 如果是编辑，就将那项的内容赋值给表单
  if (type == 1) {
    if (row) {
      addEditFormData.value.id = row.id;
      addEditFormData.value.fileId = row.fileId;
      addEditFormData.value.labId = row.labId;
      addEditFormData.value.labAddress = row.labAddress;
      addEditFormData.value.code = row.code;
      addEditFormData.value.name = row.name;
      addEditFormData.value.specificDesc = row.specificDesc;
      addEditFormData.value.cas = row.cas;
      addEditFormData.value.dangerRemark = row.dangerRemark;
      addEditFormData.value.manufacturer = row.manufacturer;
      addEditFormData.value.measure = row.measure;
      addEditFormData.value.categoryId = row.categoryId;
      addEditFormData.value.categoryName = row.categoryName;
      addEditFormData.value.quantity = row.quantity;
      addEditFormData.value.threshold = row.threshold;
      addEditFormData.value.price = row.price;
      addEditFormData.value.subjectName = row.subjectName;
      addEditFormData.value.projectName = row.projectName;
    }
  } else if (type == 0) {
    clearAddEditFormDataFunc();
  }
};

// 查询类别列表的函数
const selectCategoryListFunc = async () => {
  await selectCategoryListApi().then(res => {
    console.table(res.data);
    categoryOptions.value = res.data.map(item => {
      return {
        label: item.name,
        value: item.name
      };
    });
    // categoryOptions.value.unshift({
    //   label: "所有",
    //   value: "所有"
    // });
  });
};

// 表单查询点击事件
const querySelectClick = () => {
  console.log(1);
  selectGoodsParamData.value.page = 1;

  selectTbGoodsByPageFunc();
};

// // 表格项编辑点击事件
// const tableItemEditClick = (row: GoodsType) => {
//   console.log(row);
// };

// 表格项删除点击事件
// const tableItemDelClick = (row: GoodsType) => {
//   console.log(row);
// };

// 页码change事件
const pageChange = e => {
  console.log("page", e);
  selectGoodsParamData.value.page = e;
  selectTbGoodsByPageFunc();
};

// 最大条数change事件
const sizeChange = e => {
  console.log("size", e);
  selectGoodsParamData.value.size = e;
  selectTbGoodsByPageFunc();
};

// 表格加载标识
const isTableLoading = ref(false);

/* 查询参数 start */
const selectGoodsParamData = ref<GoodsSelectParamType>({
  // 页码
  page: 1,
  // 每页条数
  size: 10,
  // 实验室
  labAddress: "",
  // 药品柜
  code: "",
  // 药品名称
  name: "",
  // 类别
  categoryName: "",
  // 科目
  subjectName: "",
  // 项目
  projectName: ""
});

// 总共多少条
const total = ref(0);

// 货品表格数据
const goodsTableData = ref<GoodsListType>([]);

// 查询借出时所有货品的参数
const queryAllLendGoodsParams = ref({
  page: 1,
  size: 1000000,
  name: ""
});

// 借出所有货品列表
const lendAllGoodsList = ref([]);

// 借出所有货品原数据
const lendAllGoodsListY = ref([]);

// 查询借出时所有货品的函数
const selectAllLendTbGoods = async (yFlag = false) => {
  isLendGoodsLoading.value = true;
  if (yFlag) {
    await selectTbGoodsByPageApi({
      page: queryAllLendGoodsParams.value.page,
      size: queryAllLendGoodsParams.value.size,
      name: queryAllLendGoodsParams.value.name
    })
      .then(res => {
        let laD = res.data.list.map(item => {
          return {
            uid: uuidv4(),
            id: item.id,
            name: item.name,
            quantity: item.quantity,
            yLendQuantity: item.lendQuantity
          };
        });

        lendAllGoodsListY.value = JSON.parse(JSON.stringify(laD));
        console.log("拿到全部数据");
      })
      .finally(() => {
        isLendGoodsLoading.value = false;
      });
  } else {
    await selectTbGoodsByPageApi({
      page: queryAllLendGoodsParams.value.page,
      size: queryAllLendGoodsParams.value.size,
      name: queryAllLendGoodsParams.value.name
    })
      .then(res => {
        lendAllGoodsList.value = res.data.list.map(item => {
          return {
            uid: uuidv4(),
            id: item.id,
            name: item.name,
            quantity: item.quantity,
            yLendQuantity: item.lendQuantity
          };
        });
      })
      .finally(() => {
        isLendGoodsLoading.value = false;
      });
  }
};

// 查询药品列表的函数
const selectTbGoodsByPageFunc = async () => {
  isTableLoading.value = true;
  await selectTbGoodsByPageApi({
    page: selectGoodsParamData.value.page,
    size: selectGoodsParamData.value.size,
    // size: 1000000,
    labAddress: selectGoodsParamData.value.labAddress,
    code: selectGoodsParamData.value.code,
    name: selectGoodsParamData.value.name,
    categoryName: selectGoodsParamData.value.categoryName == "所有" ? "" : selectGoodsParamData.value.categoryName,
    subjectName: selectGoodsParamData.value.subjectName,
    projectName: selectGoodsParamData.value.projectName
  })
    .then(res => {
      // 计算序号
      res.data.list.forEach((good, goodIndex) => {
        good.serialNumber = (selectGoodsParamData.value.page - 1) * selectGoodsParamData.value.size + (goodIndex + 1);
        // 时间戳转换
        let createTimesTamp = Number(good.gmtCreate);
        let modifyTimesTamp = Number(good.gmtModify);
        console.log("创建时间时间戳-", createTimesTamp);
        console.log("更新时间时间戳-", modifyTimesTamp);
        // console.log(dayjs);
        good.gmtCreate = dayjs(createTimesTamp).format("YYYY-MM-DD hh:mm:ss");
        good.gmtModify = dayjs(modifyTimesTamp).format("YYYY-MM-DD hh:mm:ss");
      });
      goodsTableData.value = res.data.list;
      console.log(goodsTableData.value);

      total.value = res.data.total;
    })
    .finally(() => {
      isTableLoading.value = false;
    });
};

// 所有实验室名称的列表
const allLabNameList = ref<{ label: string; value: number }[]>([]);

// 查询所有的实验室名称的函数
const selectAllLabFunc = async () => {
  await selectAllLabApi().then(res => {
    allLabNameList.value = res.data.map((item: string, index: number) => {
      return {
        label: item,
        value: index
      };
    });
    console.table(allLabNameList.value);
  });
};

// 可以查询货品的实验室列表
const tabLabGoodsLabList = ref<selectGoodsLabListType>([]);

// 查询可以查询货品的实验室列表的函数
const tbLabSelectByGoodsFunc = async () => {
  await tbLabSelectByGoodsApi().then(res => {
    console.log("查询货品的实验室列表", res.data);
    tabLabGoodsLabList.value = res.data;
  });
};

// 货品借出/归还记录数据
const goodsLendLogData = ref([]);

// 货品借出/归还记录表格加载标识
const isLendReturnLogTableLoading = ref(false);

// 货品借出 / 归还记录表格分页总数
const lendReturnLogTableTotal = ref(0);

// 查询货品借出归还记录的参数数据
const selectGoodsLendRetParams = ref({
  tbGoodsId: "",
  page: 1,
  size: 10
});

// 查询货品借出记录数据的函数
const selectGoodsLendLogDataFunc = async () => {
  isLendReturnLogTableLoading.value = true;
  await lendGoodsSubListApi({
    tbGoodsId: selectGoodsLendRetParams.value.tbGoodsId,
    page: selectGoodsLendRetParams.value.page,
    size: selectGoodsLendRetParams.value.size
  })
    .then(res => {
      console.log("查询借出归还日志", res.data.list);
      goodsLendLogData.value = res.data.list;
      lendReturnLogTableTotal.value = res.data.total;
    })
    .finally(() => {
      isLendReturnLogTableLoading.value = false;
    });
};

// 货品借出/归还记录分页器change事件
const lendReturnLogTabPaginationChange = e => {
  selectGoodsLendRetParams.value.page = e;
  selectGoodsLendLogDataFunc();
  console.log("变化", e);
};

// init
onMounted(() => {
  console.log(localStorage.getItem("userInfo"));
  selectTbGoodsByPageFunc();
  selectCategoryListFunc();
  selectMeasureListFunc();
  selectLaboratoryListFunc();
  selectAllLabFunc();
  tbLabSelectByGoodsFunc();
  selectTbGoodsByPageFunc();
  selectAllLendTbGoods(true);
  setTimeout(() => {
    // userStore.setToken("");
    // localStorage.clear();
    // sessionStorage.clear();
    // authStore.authMenuList = [];
    // 3.重定向到登陆页
    // router.replace(LOGIN_URL);
    // ElMessage.success("退出登录成功！");
    // location.reload();
  }, 2000);
});
</script>

<style lang="scss" scoped>
.goods_wrap {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  .top_box {
    min-height: 70px;
    margin-bottom: 10px;
    .goods_top_card {
      width: 100%;
      min-height: 120px;
    }
  }
  .bottom_box {
    flex: 1;
    .goods_bottom_card {
      width: 100%;
      height: 100%;
      padding: 0;
      .el-card__body {
        padding: 0;
      }
      .pagination_box {
        display: flex;
        justify-content: flex-end;
        margin-top: 16px;

        // border: 1px solid red;
      }
    }
  }
  .operation_box {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    padding: 0 12px;
    .edit_text {
      color: blue;
      cursor: pointer;
    }
    .del_text {
      color: red;
      cursor: pointer;
    }
  }
  .add_edit_form_box {
    padding: 6px 40px 0 20px;
  }
  .export_form_box {
    padding: 20px 40px 0 20px;
  }
}
:deep(.goods_bottom_card .el-card__body) {
  padding: 14px;
}
:deep(.goods_top_card .el-form-item) {
  margin-right: 22px;
}
:deep(.goods_top_card .el-card__body) {
  padding-bottom: 0;
}
:deep(.el-descriptions__cell) {
  padding: 6px 16px !important;
}

:deep(.good_detail_dialog) {
  margin-bottom: 0px;
}

:deep(.good_lend_log_table) {
  .el-table__cell {
    padding: 6px 0px;
  }
}
</style>
